import { createElement, serializeLabel } from '../utils'

export default (expression: any, { metadata }: any, map: any) => {
  const { stops } = expression
  return createElement('ul', {
    classes: ['list', 'list--icons'],
    content: stops.map(([value, image]: any) => {
      const { height, width, data } =
        map.style.imageManager.images[image]?.data || {}
      if (!height || !width || !data) {
        return null
      }
      const size = Math.max(width, height)
      const canvas = createElement('canvas', {
        attributes: { width: size, height: size },
      })
      const context = canvas.getContext('2d')
      const offsetX = (size - width) / 2
      const offsetY = (size - height) / 2
      const imageData = new ImageData(
        Uint8ClampedArray.from(data),
        width,
        height
      )
      context.putImageData(imageData, offsetX, offsetY)
      return createElement('li', {
        content: [
          createElement('img', {
            classes: ['icon'],
            attributes: { src: canvas.toDataURL() },
          }),
          serializeLabel(value, metadata),
        ],
      })
    }),
  })
}
